import Vue from 'vue'
import VueRouter from 'vue-router'
// 路由路径都放在另一个地方
import routes from './routes'
// 为了获取store里面的值
import store from '@/store'
Vue.use(VueRouter)
let originpush = VueRouter.prototype.push;
let originreplace = VueRouter.prototype.replace;
VueRouter.prototype.push=function(location,reslove,reject){
    if(reslove && reject){
        originpush.call(this,location,reslove,reject);
    }else{
        originpush.call(this,location,()=>{},()=>{})
    }
}
VueRouter.prototype.replace = function(location,reslove,reject){
    if(reslove && reject){
        originreplace.call(this,location,reslove,reject)
    }else{
        originreplace.call(this,location,()=>{},()=>{})
    }
}
const router =  new VueRouter({
    routes,
    scrollBehavior (to, from, savedPosition) {
        return { x: 0, y: 0 }
      }
})
// 路由守卫
router.beforeEach(async (to,from,next)=>{
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if(token){
        if(to.path == '/login'){
            // 登录成功后想要跳回登录页面  会跳回home页面
            next('/home');
        }else{
            if(name){
                // 登录成功有用户信息的时候才会 走这一步
                next()
            }else{
                try{
                    //没有用户信息  去请求用户信息
                    await store.dispatch('getUserInfo');
                    next();
                }catch(error){
                    // 删除数据库里面的token 数据和 用户数据  以及本地存储的token
                    await store.dispatch('loginOut');
                    next('/login')
                }
            }
        }
    }else{
        next();
    }
})
export default router;